package pers.lance.easystruct1.controller;

import pers.lance.easystruct1.action.Action;
import pers.lance.easystruct1.annotation.RequestMapping;
import pers.lance.easystruct1.manager.ClassManager;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ Author     ：LILA3
 * @ Date       ：Created in 7:26 PM 7/24/2018
 */
public class SerlvetController extends HttpServlet {

    List<Class<?>> actionClassList = null;
    Map<String, Action> routerMap = null;
    ClassManager classManager = null;

    @Override
    public void init() throws ServletException {
        try {
            classManager = ClassManager.getInstance();
            scanAction();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        super.init();
    }

    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        String url = ((HttpServletRequest) req).getServletPath();
        String method = ((HttpServletRequest) req).getMethod();
        String key = url + "_" + method;
        Action action = routerMap.get(key.toLowerCase());
        if (action != null) {
            action.process((HttpServletRequest) req, (HttpServletResponse) res);
        } else {
            super.service(req, res);
        }
    }

    private void scanAction() {
        try {
            classManager.scan("pers.lance.easystruct1.action");
            actionClassList = classManager.getClasses();
            routerMap = new HashMap<String, Action>();
            for (Class actionClazz : actionClassList) {
                RequestMapping requestMapping = (RequestMapping) actionClazz.getAnnotation(RequestMapping.class);
                if (requestMapping == null) {
                    continue;
                }
                String url = requestMapping.value();
                String method = requestMapping.requestMethod().getName();
                routerMap.put(url + "_" + method, (Action) actionClazz.newInstance());
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }
}
